/**
 * Copyright(c)2013 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.common.dialect;

/**
 * @description A dialect for Oracle 9i/10g databases
 * @author aokunsang
 * @date 2013-4-18
 */
public class OracleDialect extends Dialect {

	/* (non-Javadoc)
	 * @see com.pmc.dwa.common.dialect.Dialect#getLimitString(java.lang.String, int, int)
	 */
	@Override
	public String getLimitString(String sql, int offset, int limit) {
		sql = sql.trim();
 		boolean isForUpdate = false;
 		if ( sql.toLowerCase().endsWith(" for update") ) {
 			sql = sql.substring( 0, sql.length()-11 );
 			isForUpdate = true;
 		}
 
 		StringBuffer pagingSelect = new StringBuffer( sql.length()+100 );
 		if (offset > 0) {  //不是第一页
 			pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
 		}
 		else {
 			pagingSelect.append("select * from ( ");
 		}
 		pagingSelect.append(sql);
 		if (offset > 0) {
 			pagingSelect.append(" ) row_ where rownum <= "+(limit+offset)+") where rownum_ > "+offset);
 		}
 		else {
 			pagingSelect.append(" ) where rownum <= "+limit);
 		}
 
 		if ( isForUpdate ) {
 			pagingSelect.append( " for update" );
 		}
 
 		return pagingSelect.toString();
	}
	
	public static String getCurrentTimestampSelectString() {
 		return "select sysdate from dual";   //select systimestamp from dual
 	}
	
	public static String getQuerySequencesString() {
		return    " select sequence_name from all_sequences"
				+ "  union"
				+ " select synonym_name"
				+ "   from all_synonyms us, all_sequences asq"
				+ "  where asq.sequence_name = us.table_name"
				+ "    and asq.sequence_owner = us.table_owner";
	}
	
	public static String getSelectGUIDString() {
		return "select rawtohex(sys_guid()) from dual";
	}
}
